package com.olc.railing.camera;

import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.view.SurfaceHolder;

import com.google.gson.Gson;
import com.olc.railing.R;
import com.olc.railing.base.BaseActivity;
import com.olc.railing.base.BaseApplication;
import com.olc.railing.busniess.DataBusiness;
import com.olc.railing.busniess.LampControler;
import com.olc.railing.busniess.MyThreadPoolExecutor;
import com.olc.railing.constant.Constants;
import com.olc.railing.model.BillInfo;
import com.olc.railing.model.EventInfo;
import com.olc.railing.model.GasOrderInfo;
import com.olc.railing.model.PayStatus;
import com.olc.railing.model.UserInfo;
import com.olc.railing.orm.BillInfoDao;
import com.olc.railing.orm.UserInfoDao;
import com.olc.railing.utils.CommUtils;
import com.olc.railing.utils.FileUtils;
import com.olc.railing.utils.MyLog;
import com.olc.railing.utils.SharedUtils;
import com.olc.railing.utils.TimeUtils;
import com.olc.railing.utils.ZipUtils;
import com.tyxh.paylibrary.bean.GasTradeInfoBody;
import com.tyxh.paylibrary.exception.BaseException;
import com.tyxh.paylibrary.model.GasPayBusiness;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;


public class VedioActivity extends BaseActivity implements VideoRecord{
    private static final String TAG = VedioActivity.class.getSimpleName();
    private static final int AUTO_END_RECORD_FLAG = 0;
    private static final int MANUAL_END_RECORD_FLAG = 1;
    private CameraPreview cameraPreview;

    private static final int  TIME_DISTACE = 120*1000;
  //  private boolean isHasCamera = false;
    private static VideoRecordManager videoRecordManager;
    private String mPlateNo;

    private MyHandler handler = new MyHandler(this);

    private BusinessHandler businessHandler = new BusinessHandler(this);

    private static class BusinessHandler extends Handler {
        private WeakReference<VedioActivity> vedioActivityWeakReference;

        private BusinessHandler(VedioActivity vedioActivity) {
            vedioActivityWeakReference = new WeakReference<>(vedioActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DataBusiness.NOTICE_GAS_FAIL:
                    String[] datas = null;
                    if(msg.obj instanceof String){
                        String data = (String) msg.obj;
                        MyLog.e(MyLog.TAG,"NOTICE_GAS_FAIL data "+data);
                        datas =  data.split("\\|");
                    }else{
                        MyLog.e(MyLog.TAG,"NOTICE_GAS_FAIL no change ");
                    }
                    int times = msg.arg1;
                    String billUUid = datas[0];
                    String error = datas[1];
                    MyLog.e(MyLog.TAG,"NOTICE_GAS_FAIL billUUid "+billUUid +" times: "+times+" error: "+error);
                    if("102".equals(error)){//其他渠道支付或者通知三次都失败，就提示用户使用其他渠道支付
                        new BillInfoDao(vedioActivityWeakReference.get()).deleteByOrderNo(billUUid);
                        vedioActivityWeakReference.get().playMedia(R.raw.finish_trade_repeat_pay);
                        vedioActivityWeakReference.get().payStatus = PayStatus.PAY_FAIL;
                    }else{
                        if(times>2){//告知加油站失败，重复三次
                            new BillInfoDao(vedioActivityWeakReference.get()).deleteByOrderNo(billUUid);
                            vedioActivityWeakReference.get().playMedia(R.raw.tradefail);
                            vedioActivityWeakReference.get().payStatus = PayStatus.PAY_FAIL;
                        }else{
                            DataBusiness.getInstance(vedioActivityWeakReference.get()).notifyGasStation(this, billUUid);
                        }

                    }
                    break;

                case DataBusiness.NOTICE_GAS_SUCCESS:
                    String[] uuidAndInvoices = null;
                    if(msg.obj instanceof String){
                        String uuidAndInvoice = (String) msg.obj;
                        MyLog.e(MyLog.TAG,"NOTICE_GAS_SUCCESS uuidAndInvoices "+uuidAndInvoice);
                        uuidAndInvoices =  uuidAndInvoice.split("\\|");
                    }else{
                        MyLog.e(MyLog.TAG,"NOTICE_GAS_SUCCESS no change ");
                    }
                    String uuid = uuidAndInvoices[0];
                    String invoiceUrl = uuidAndInvoices[1];
                    MyLog.e(MyLog.TAG,"NOTICE_GAS_SUCCESS uuid "+uuid+" invoiceUrl "+invoiceUrl);

                    EventBus.getDefault().post(  new EventInfo(Constants.START_UPLOAD_ORDER_TO_SERVER,uuid));
                    vedioActivityWeakReference.get().syncInvoiceToBigScreen(invoiceUrl);
                    break;

                case DataBusiness.PATCH_ORDER_FAIL:
                    String error1 = (String) msg.obj;
                    if ("102".equals(error1)) {
                        vedioActivityWeakReference.get().playMedia(R.raw.finish_trade_repeat_pay);
                    } else {
                        vedioActivityWeakReference.get().playMedia(R.raw.patch_order_fail);
                    }
                    vedioActivityWeakReference.get().payStatus = PayStatus.PAY_FAIL;
                    break;

                case DataBusiness.PATCH_ORDER_SUCCESS:
                    DataBusiness.getInstance(vedioActivityWeakReference.get()).etcPay(plateNo, this);
                    break;

                case DataBusiness.ETC_PAY_SUCCESS:
                    GasTradeInfoBody gasTradeInfoBody = GasPayBusiness.getInstance().getTradInfoBody();
                    String bill_info_data = GasPayBusiness.getInstance().getBillInfo().toString();
                    String gas_info_data = new Gson().toJson(gasTradeInfoBody);
                    BillInfo billInfo = new BillInfo();
                    billInfo.setBillInfoData(bill_info_data);
                    billInfo.setGasInfoData(gas_info_data);
                    billInfo.setUploadStatus(0);
                    billInfo.setBillUuid(CommUtils.getUUId());
                   // billInfo.setGasOrderId(DataBusiness.getInstance(vedioActivityWeakReference.get()).getmGasOrderInfo().getOtherOrderId());
                    new BillInfoDao(vedioActivityWeakReference.get()).insert(billInfo);
                    DataBusiness.getInstance(vedioActivityWeakReference.get()).notifyGasStation(this,billInfo.getBillUuid());
                    break;

                case DataBusiness.ETC_PAY_FAIL:
                    vedioActivityWeakReference.get().payStatus = PayStatus.PAY_FAIL;
                    BaseException baseException = (BaseException) msg.obj;
                    vedioActivityWeakReference.get().etcPaFial(baseException);
                    break;

                case DataBusiness.NO_OIL_GUN_NO:
                    vedioActivityWeakReference.get().playMedia(R.raw.add_oil_gun_no);
                    vedioActivityWeakReference.get().payStatus = PayStatus.NO_PAY;
                    break;

                case DataBusiness.N0_RECOGINISE_VEHPLATE:
                    vedioActivityWeakReference.get().playMedia(R.raw.no_recognise_vheplate_no);
                    vedioActivityWeakReference.get().payStatus = PayStatus.NO_PAY;
                    break;





            }
        }

    }


    private static class MyHandler extends Handler {
        private WeakReference<VedioActivity> vedioActivityWeakReference;

        private MyHandler(VedioActivity vedioActivity) {
            vedioActivityWeakReference = new WeakReference<>(vedioActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 202:
                    if(videoRecordManager!=null){
                        videoRecordManager.stop();
                    }
                    removeMessages(201);
                    sendEmptyMessageDelayed(201,5*1000);
                    break;

                case 201:
                    if(videoRecordManager!=null){
                        videoRecordManager.startRecord();
                    }
                    removeMessages(202);
                    sendEmptyMessageDelayed(202,TIME_DISTACE);
                    break;

                case 500:
                    int falg = msg.arg1;
                    MyLog.d(MyLog.TAG,"结束标志 flag = "+falg);
                    if(falg == AUTO_END_RECORD_FLAG){
                        isOpenGreen = false;
                        isOpenRed = false;
                        postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                LampControler.closeRedLamp();
                                LampControler.openGreenLamp();
                                vedioActivityWeakReference.get().playMedia(new int[]{R.raw.tradefinish,R.raw.jiayoujieshu},0);
                                vedioActivityWeakReference.get().payStatus = PayStatus.PAY_SUCCESS;
                                MyLog.d(MyLog.TAG,"关闭录像");

                                vedioActivityWeakReference.get().finish();
                            }
                        },1000);
                    }else if(falg == MANUAL_END_RECORD_FLAG){
                       // vedioActivityWeakReference.get().playMedia(R.raw.jiayoujieshu);
                        MyLog.d(MyLog.TAG,"关闭录像");
                        vedioActivityWeakReference.get().finish();
                    }

                    break;
            }
        }
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_camre_layout;
    }
    @Override
    protected void init() {
        mPlateNo = getIntent().getStringExtra("mPlateNo");
        initCameraView();
    }


    private void initCameraView() {
        cameraPreview = (CameraPreview) findViewById(R.id.capture_preview);
        videoRecordManager = new VideoRecordManager(this,mPlateNo);
        videoRecordManager.initRecord();
        if(cameraPreview.start(1)){
            handler.sendEmptyMessageDelayed(201,1000);
        }

    }





    @Override
    public Camera getCamera() {
        return cameraPreview.mCamera;
    }

    @Override
    public SurfaceHolder getSurfaceHolder() {
        return cameraPreview.mHolder;
    }



    @Override
    public void endOil() {
        super.endOil();
        MyLog.d(MyLog.TAG,"VedioActivity endOil ");
        playMedia(R.raw.jiayoujieshu);
        handler.removeCallbacksAndMessages(null);
        releaseData();
        MyThreadPoolExecutor.getMyThreadPoolInstance().getMyThreadPoolExecutor().execute(new Runnable() {
            @Override
            public void run() {
                saveFile(MANUAL_END_RECORD_FLAG);
            }
        });

    }


    /**
     * 同步信息到大屏，结束录像，结束加油
     * @param invoiceUrl
     */
    public void syncInvoiceToBigScreen(String invoiceUrl) {
        MyLog.d(MyLog.TAG,"notifyGasSuccess "+invoiceUrl);
        isPaySuccess = true;
        UserInfo userInfo  = new UserInfoDao(BaseApplication.getApplication()).queryBySerialNo(SharedUtils.getSerialNo(BaseApplication.getApplication())+"");
        if(userInfo!=null){
            GasOrderInfo mGasOrderInfo = DataBusiness.getInstance(this).getmGasOrderInfo();
            userInfo.setCloseType(Constants.AUTO_CLOSE);//自动关闭
            userInfo.setOcrVehPlate(plateNo);
            userInfo.setEtcPayStatus(payStatus.code+"");
            userInfo.setAdress(GasPayBusiness.getInstance().getGasStationName());
            userInfo.setPrePrice(mGasOrderInfo.getTotalMoney());
            userInfo.setDiscountPrice(mGasOrderInfo.getTotalMoney()-mGasOrderInfo.getPayMoney());
            userInfo.setActualPrice(mGasOrderInfo.getPayMoney());
            userInfo.setOilGunNo(SharedUtils.getOilGunNo(BaseApplication.getApplication()));
            userInfo.setOilLiter(mGasOrderInfo.getLitter()+mGasOrderInfo.getUnit());
            userInfo.setOilType(mGasOrderInfo.getGoodsName());
            userInfo.setUnitPrice(CommUtils.divide(String.valueOf(mGasOrderInfo.getUnitPrice()),"100",2));
            userInfo.setOperator(mGasOrderInfo.getWorkNum());
            userInfo.setTradeNo(mGasOrderInfo.getOtherOrderId());
            userInfo.setTradeTime(TimeUtils.getTime("yyyy/MM/dd HH:mm",System.currentTimeMillis()+""));
            userInfo.setNetAdress(invoiceUrl);
            new UserInfoDao(BaseApplication.getApplication()).update(userInfo);
            if(socketClient!=null){
                socketClient.sendStrData(new Gson().toJson(userInfo));
            }
        }

        handler.removeCallbacksAndMessages(null);
        releaseData();
        MyThreadPoolExecutor.getMyThreadPoolInstance().getMyThreadPoolExecutor().execute(new Runnable() {
            @Override
            public void run() {
                saveFile(AUTO_END_RECORD_FLAG);
            }
        });
    }

    /**
     * 释放资源
     */
    private void releaseData(){
        MyLog.d(MyLog.TAG, "releaseData");

        if(videoRecordManager!=null){
            videoRecordManager.stop();
        }
        if(cameraPreview!=null){
            cameraPreview.stop();
        }
    }



    @Override
    protected void fetchOrder() {
        MyLog.e(MyLog.TAG,"fetchOrder");
        DataBusiness.getInstance(this).fetchOrderAndPay(plateNo, businessHandler);
    }

    private synchronized void saveFile(int flag) {
        MyLog.d(MyLog.TAG,"开始保存文件");

        UserInfo userInfo =  new UserInfoDao(this).queryBySerialNo(SharedUtils.getSerialNo(BaseApplication.getApplication())+"");
        if(userInfo!=null){
            MyLog.d("userinfo","开始保存文件"+userInfo.toString());
            userInfo.setRecordFileName(videoRecordManager.getDestinationFileName());
            new UserInfoDao(this).update(userInfo);
        }
        try {
            ZipUtils.ZipFolder(videoRecordManager.getSorceFilePath(), BaseApplication.getDestinationFileDir(),videoRecordManager.getDestinationFileName());
        } catch (Exception e) {
            e.printStackTrace();
            MyLog.d(MyLog.TAG,"压缩文件异常");
        }
        MyLog.d(MyLog.TAG,"待删除文件"+ BaseApplication.getSourceFileDir());
        FileUtils.deleteFile(BaseApplication.getSourceFileDir());

        Message message = handler.obtainMessage();
        message.arg1 = flag;
        message.what = 500;
        handler.sendMessage(message);
    }
}
